package cn.mcsys.platform.core.service;

import cn.mcsys.myadmin.common.config.Global;
import cn.mcsys.myadmin.common.utils.SFTPUtils;
import cn.mcsys.myadmin.dubbo.service.BackService;
import cn.mcsys.myadmin.modules.mobile.entity.AirRealtimeUserCount;
import cn.mcsys.myadmin.modules.mobile.entity.AirRealtimeUserOrigin;
import cn.mcsys.myadmin.modules.mobile.entity.AirUserFlowCount;
import com.jcraft.jsch.SftpException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletContext;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class SFTPTimer {

    public static final String SFTP_DIR = "sftpfile";

    public static final String YIDONG_SFTP_SERVER_DIR = "/home/sftp";

    public static final String USER_FLOW_COUNT = "user_flow_user";

    public static final String REALTIME_USER_COUNT = "realtime_user_count";

    public static final String REALTIME_USER_ORIGIN = "realtime_user_origin";

    @Autowired
    private ServletContext servletContext;

    @Autowired
    private BackService backService;

    /**
     * 登录SFTP服务器查看是否有新文件,有就解析入库(移动数据)
     *
     * @throws SftpException
     * @throws IOException
     * @throws ParseException
     */
    public void checkSFTPFile() throws SftpException, IOException, ParseException {
        System.out.println("进入SFTP定时器================================");
        String path = servletContext.getRealPath("/");
        path += SFTP_DIR;
//        获取本地的SFTP文件
//        列出本地的保存sftp文件的目录
        File dir = new File(path);
        System.out.println("本地文件路径:"+path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File[] files = dir.listFiles();
        List<String> mySFTPFiles = new ArrayList<>();
        for (File file : files) {
            mySFTPFiles.add(file.getName());
        }
        System.out.println("SFTP登录前=====================================");
        SFTPUtils sftp = new SFTPUtils(Global.getConfig("sftp.username"), Global.getConfig("sftp.password"), Global.getConfig("sftp.host"), Integer.valueOf(Global.getConfig("sftp.port")));
        sftp.login();
        System.out.println("登录成功");
        Vector<?> ls = sftp.listFiles(YIDONG_SFTP_SERVER_DIR);
        System.out.println("查看有多少个SFPT文件:"+ls.size());
        List<String> newSFTPFile = new ArrayList<>();
//        下载sftp文件
        for (Object sftpFile : ls) {
            String string = sftpFile.toString();//对象toString
            if (string.endsWith("txt"))//如果是以txt结尾，那就进入
            {
                //根据规律文件名切割字符串
                String substring = string.substring(string.lastIndexOf(" "), string.length());
                String sftpFileName = substring.trim();
//                System.out.println(sftpFileName);
//                如果本地不包含该文件就下载该文件并解析
                if (!mySFTPFiles.contains(substring.trim())) {
                    String dirSFTPFile = dir + File.separator + sftpFileName;
//                    System.out.println("文件路径:"+dirSFTPFile+"====================================================");
                    newSFTPFile.add(dirSFTPFile);
//                    要具体到文件中
                    sftp.download(YIDONG_SFTP_SERVER_DIR, sftpFileName, dirSFTPFile);
//                    System.out.println(sftpFileName + "-------下载完成");
                }
            }
        }

//        读入sftp文件
        List<AirRealtimeUserCount> airRealtimeUserCounts = new ArrayList<>();
        List<AirUserFlowCount> airUserFlowCounts = new ArrayList<>();
        List<AirRealtimeUserOrigin> airRealtimeUserOrigins = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (String sftpFile : newSFTPFile) {
            File file = new File(sftpFile);
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String sLine = null;
            if (sftpFile.contains(USER_FLOW_COUNT)) {
                while ((sLine = br.readLine()) != null) {
                    sLine = sLine.trim();
                    System.out.println("sline:" + sLine);
                    String[] ary = sLine.split("\\|");
                    AirUserFlowCount airUserFlowCount = new AirUserFlowCount();
                    airUserFlowCount.setStartDateTime(format.parse(ary[0]));
                    airUserFlowCount.setAreaId(Integer.valueOf(ary[1]));
                    airUserFlowCount.setUserInflowCount(Long.parseLong(ary[2]));
                    airUserFlowCount.setUserOutflowCount(Long.parseLong(ary[3]));
                    airUserFlowCounts.add(airUserFlowCount);
                }
            } else if (sftpFile.contains(REALTIME_USER_COUNT)) {
                while ((sLine = br.readLine()) != null) {
                    sLine = sLine.trim();
                    System.out.println("sline:" + sLine);
                    String[] ary = sLine.split("\\|");
                    AirRealtimeUserCount airRealtimeUserCount = new AirRealtimeUserCount();
                    airRealtimeUserCount.setStartDateTime(format.parse(ary[0]));
                    airRealtimeUserCount.setAreaId(Integer.valueOf(ary[1]));
                    airRealtimeUserCount.setUserCount(Long.parseLong(ary[2]));
                    airRealtimeUserCounts.add(airRealtimeUserCount);
                }
            }else if (sftpFile.contains(REALTIME_USER_ORIGIN)) {
                while ((sLine = br.readLine()) != null) {
                    sLine = sLine.trim();
                    System.out.println("sline:" + sLine);
                    String[] ary = sLine.split("\\|");
                    AirRealtimeUserOrigin airRealtimeUserOrigin = new AirRealtimeUserOrigin();
                    airRealtimeUserOrigin.setStartDateTime(format.parse(ary[0]));
                    airRealtimeUserOrigin.setAreaId(Integer.valueOf(ary[1]));
                    airRealtimeUserOrigin.setOriginAtt(Integer.valueOf(ary[2]));
                    airRealtimeUserOrigin.setOriginName(String.valueOf(ary[3]));
                    airRealtimeUserOrigin.setUserCount(Long.parseLong(ary[4]));
                    airRealtimeUserOrigins.add(airRealtimeUserOrigin);
                }
            }
            br.close();
        }
        if (airRealtimeUserCounts != null && airRealtimeUserCounts.size() > 0) {
            backService.batchInsertRealtimeUserCount(airRealtimeUserCounts);
        }
        if (airUserFlowCounts != null && airUserFlowCounts.size() > 0) {
            backService.batchInsertUserFlowCount(airUserFlowCounts);
        }
        if (airRealtimeUserOrigins != null && airRealtimeUserOrigins.size() > 0) {
            backService.batchInsertRealtimeUserOrigin(airRealtimeUserOrigins);
        }
        sftp.logout();
    }


}
